import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { asyncRouter } from './router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
// 前置守卫  在页面切换的时候就会执行
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 进度条功能
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/') // next有路径不会走后置守卫
      NProgress.done()
    } else {
      if (!store.getters.userId) { // 在经过路由前置守卫的时候获取用户资料
        const { roles } = await store.dispatch('user/getUserInfo')
        // action是异步操作 必须强制等待获取完数据才可跳转  从登录用户的角色上获取权限信息
        const filterRoutes = asyncRouter.filter(item => { // 筛选出用户可访问的路由
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加筛选后的路由
        next(to.path) // 动态添加路由需要重新加载一下 让路由有信息 路由缺陷
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
